package com.windowes.weichang.component.jpush;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import cn.jpush.api.schedule.ScheduleResult;
import com.windowes.weichang.common.ServerResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/***
 *
 * @author: yangqing
 * @email: qing.yang@bangdao-tech.com
 * @createTime: 2018/6/1 下午10:15
 * @description:
 *
 **/
@Component
@Slf4j
public class JPushService {

    @Autowired
    JpushConfig jpushConfig;

    public ServerResponse pushUser(String alert, String... alis) {
        JpushAKMK user = jpushConfig.getUser();
        return push(user.getMasterKey(), user.getAppKey(), alert, alis);
    }

    public ServerResponse pushShop(String alert, String... alis) {
        JpushAKMK user = jpushConfig.getShop();
        return push(user.getMasterKey(), user.getAppKey(), alert, alis);
    }

    private ServerResponse push(String masterKey,
                                String appKey, String alert, String[] alis) {

        JPushClient jpushClient = new JPushClient(masterKey, appKey, null, ClientConfig.getInstance());
        PushPayload payload = buildPushObject_all_alias_alert(alert, alis);
        try {
            PushResult result = jpushClient.sendPush(payload);
            log.error("推送结果: {0}", result);
            return ServerResponse.createBySuccess(result);
        } catch (APIConnectionException e) {
            log.error("推送异常APIConnectionException: {0}", e);
        } catch (APIRequestException e) {
            log.error("推送异常APIRequestException: {0}", e);
        }
        return ServerResponse.createByErrorMessage("推送异常!");
    }

    public static PushPayload buildPushObject_all_alias_alert(String alert, String... alis) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(alis))
                .setNotification(Notification.alert(alert))
                .build();
    }


    /**
     * 定时推送
     *
     * @param name
     * @param time 2016-07-30 12:30:25
     */
    public ServerResponse<String> scheduleUser(String alert, String name, String time, String... alis) {
        JpushAKMK user = jpushConfig.getUser();
        return schedule(user.getMasterKey(), user.getAppKey(), alert, name, time, alis);
    }

    /**
     * 定时推送
     *
     * @param name
     * @param time 2016-07-30 12:30:25
     */
    public ServerResponse<String> scheduleShop(String alert, String name, String time, String... alis) {
        JpushAKMK user = jpushConfig.getShop();
        return schedule(user.getMasterKey(), user.getAppKey(), alert, name, time, alis);
    }

    /**
     * 定时推送
     *
     * @param name
     * @param time 2016-07-30 12:30:25
     */
    public ServerResponse<String> schedule(String masterKey,
                                           String appKey, String alert, String name, String time, String... alis) {
        JPushClient jpushClient = new JPushClient(masterKey,
                appKey, null, ClientConfig.getInstance());
        PushPayload push = buildPushObject_all_alias_alert(alert, alis);
        try {
            ScheduleResult result = jpushClient.createSingleSchedule(name, time, push);
            log.info("schedule result is " + result);
            String scheduleId = result.getSchedule_id();
            return ServerResponse.createBySuccess(scheduleId);
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
            return ServerResponse.createByError();
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.error("HTTP Status: " + e.getStatus());
            log.error("Error Code: " + e.getErrorCode());
            log.error("Error Message: " + e.getErrorMessage());
        }
        return ServerResponse.createByError();
    }

    /**
     * 取消定时推送
     */
    public void cancleScheduleUser(String scheduleId) {
        JpushAKMK user = jpushConfig.getUser();
        cancleSchedule(user.getMasterKey(), user.getAppKey(), scheduleId);
    }

    /**
     * 取消定时推送
     */
    public void cancleScheduleShop(String scheduleId) {
        JpushAKMK user = jpushConfig.getShop();
        cancleSchedule(user.getMasterKey(), user.getAppKey(), scheduleId);
    }

    /**
     * 取消定时推送
     */
    public void cancleSchedule(String masterKey,
                               String appKey, String scheduleId) {
        if (StringUtils.isEmpty(scheduleId)) {
            log.error("JPushService.cancleSchedule:scheduleId不能为空");
            return;
        }
        JPushClient jpushClient = new JPushClient(masterKey, appKey, null, ClientConfig.getInstance());
        try {
            jpushClient.deleteSchedule(scheduleId);
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.error("HTTP Status: " + e.getStatus());
            log.error("Error Code: " + e.getErrorCode());
            log.error("Error Message: " + e.getErrorMessage());
        }
    }


}
